<script lang="ts" setup>
import type { NotificationItem } from '@vben/layouts';

import { computed, ref, watch } from 'vue';
import { $t } from '@vben/locales';
import { AuthenticationLoginExpiredModal, useVbenModal } from '@vben/common-ui';
import { useAppConfig, useWatermark } from '@vben/hooks';
import {
  BasicLayout,
  LockScreen,
  Notification,
  UserDropdown,
} from '@vben/layouts';
import { preferences } from '@vben/preferences';
import { useAccessStore, useUserStore } from '@vben/stores';

import { storeToRefs } from 'pinia';

import { useAuthStore, usePreferencesStore } from '#/store';
import LoginForm from '#/views/_core/authentication/login.vue';

import DevPage from './modal/dev/index.vue';
import UserPage from './modal/user/index.vue';

const [UserModal, modalApi] = useVbenModal({
  // 连接抽离的组件
  connectedComponent: UserPage,
});

const [DevModal, devModalApi] = useVbenModal({
  // 连接抽离的组件
  connectedComponent: DevPage,
});

const notifications = ref<NotificationItem[]>([
  {
    avatar: 'https://avatar.vercel.sh/vercel.svg?text=VB',
    date: '3小时前',
    isRead: true,
    message: '描述信息描述信息描述信息',
    title: '收到了 14 份新周报',
  },
  {
    avatar: 'https://avatar.vercel.sh/1',
    date: '刚刚',
    isRead: false,
    message: '描述信息描述信息描述信息',
    title: '朱偏右 回复了你',
  },
  {
    avatar: 'https://avatar.vercel.sh/1',
    date: '2024-01-01',
    isRead: false,
    message: '描述信息描述信息描述信息',
    title: '曲丽丽 评论了你',
  },
  {
    avatar: 'https://avatar.vercel.sh/satori',
    date: '1天前',
    isRead: false,
    message: '描述信息描述信息描述信息',
    title: '代办提醒',
  },
]);

const userStore = useUserStore();
const authStore = useAuthStore();
const accessStore = useAccessStore();
const { destroyWatermark, updateWatermark } = useWatermark();
const showDot = computed(() =>
  notifications.value.some((item) => !item.isRead),
);
const preferencesStore = usePreferencesStore();
const { title } = storeToRefs(preferencesStore);
const avatar = computed(() => {
  return userStore.userInfo?.avatar && userStore.userInfo.avatar
    ? userStore.userInfo.avatar
    : preferences.app.defaultAvatar;
});

const toHome = () => {
  const { baseURL } = useAppConfig(import.meta.env, import.meta.env.PROD);
  let domain = `${document.location.protocol}//${window.location.host}`;
  if (baseURL) {
    domain = baseURL;
  }
  const win = window.open(domain, '_blank');
  win?.focus();
};

const menus = computed(() => {
  const roles = userStore.userRoles;
  const baseMenu = [
    {
      handler: () => toHome(),
      icon: 'ri:home-line' as any,
      text: $t('admin.websiteHome'),
    },
    {
      handler: () => modalApi.open(),
      icon: 'ri:user-settings-line' as any,
      text: $t('admin.accountInfo'),
    },
  ];

  if (roles.includes('super')) {
    baseMenu.push({
      handler: () => devModalApi.open(),
      icon: 'ri:terminal-box-line',
      text: $t('admin.devPanel'),
    });
  }

  return baseMenu;
});

async function handleLogout() {
  await authStore.logout(false);
}

function handleNoticeClear() {
  notifications.value = [];
}

function handleMakeAll() {
  notifications.value.forEach((item) => (item.isRead = true));
}
watch(
  () => preferences.app.watermark,
  async (enable) => {
    if (enable) {
      await updateWatermark({
        content: `${userStore.userInfo?.username}`,
      });
    } else {
      destroyWatermark();
    }
  },
  {
    immediate: true,
  },
);
</script>

<template>
  <BasicLayout :app-name="title" @clear-preferences-and-logout="handleLogout">
    <template #user-dropdown>
      <DevModal />
      <UserModal />
      <UserDropdown
        :avatar
        :description="
          userStore.userInfo?.signature || $t('admin.keepWordsSecret')
        "
        :menus="menus"
        :text="
          userStore.userInfo?.user_nickname && userStore.userInfo.user_nickname
            ? userStore.userInfo?.user_nickname
            : userStore.userInfo?.user_login
        "
        @logout="handleLogout"
      />
    </template>
    <template #notification>
      <Notification
        :dot="showDot"
        :notifications="notifications"
        @clear="handleNoticeClear"
        @make-all="handleMakeAll"
      />
    </template>
    <template #extra>
      <AuthenticationLoginExpiredModal
        v-model:open="accessStore.loginExpired"
        :avatar
      >
        <LoginForm />
      </AuthenticationLoginExpiredModal>
    </template>
    <template #lock-screen>
      <LockScreen :avatar @to-login="handleLogout" />
    </template>
  </BasicLayout>
</template>
